package com.patMall.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mysql.jdbc.log.Log;
import com.patMall.entity.Comment;
import com.patMall.entity.CommentImg;
import com.patMall.entity.User;
import com.patMall.service.CommentImgService;
import com.patMall.service.CommentService;
import com.patMall.service.UserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Author 750909637@qq.com
 * @PackageName patMall
 * @Package com.patMall.controller
 * @Date 2024/2/18 10:46
 * @Version 1.0
 */
@Controller
@RequestMapping("comment")
public class commentController {
    @Resource
    private CommentService commentService;
    @Resource
    private CommentImgService commentImgService;
    @Resource
    private UserService userService;
    @PostMapping("addComment")
    @ResponseBody
    public Object addComment(@RequestParam("files1") MultipartFile files1,
                             @RequestParam("files2") MultipartFile files2,
                             @RequestParam("files3") MultipartFile files3,
                             @RequestParam("userId") String userId,
            @RequestParam("commodityId") String commodityId,
            @RequestParam("commentContent") String commentContent,HttpServletRequest request) {
        Integer userId1 = Integer.parseInt(userId);
        List<MultipartFile> files = new ArrayList<MultipartFile>();
        files.add(files1);
        files.add(files2);
        files.add(files3);
        Integer commodityId1 = Integer.parseInt(commodityId);
        Comment comment = new Comment(userId1,commentContent,commodityId1);
        Map map = new HashMap();
        CommentImg commentImg = new CommentImg();
        int count = commentService.addComment(comment);
        if (count == 1) {
            map.put("code",0);
            for (MultipartFile file : files) {
                // 默认成功
                map.put("code", 0);
                // 假设0表示成功
                if (file != null && file.getContentType().startsWith("image/")) {
                    String originalFilename = file.getOriginalFilename();
                    String fileExtension = FilenameUtils.getExtension(originalFilename);
                    // 获取文件扩展名
                    if (!"jpg".equalsIgnoreCase(fileExtension) && !"png".equalsIgnoreCase(fileExtension)) {
                        continue;
                        // 不是有效的图像文件，跳过
                    }

                    User user = userService.getUserId(comment.getUserId());
                    String baseDir = "P:/pat_mall/commentImg/";
                    System.err.println(baseDir);
                    String subDir = comment.getCommodityId() + "_" + comment.getUserId() + "_" + user.getUsername() + "_commentImg/";
                    File subDirFile = new File(baseDir, subDir);
                    if (!subDirFile.exists()) {
                        subDirFile.mkdirs();
                        // 确保子目录存在
                    }

                    // 使用UUID作为文件名的一部分来避免冲突
                    String newFileName = System.currentTimeMillis() + "_" + originalFilename;
                    String savePath = baseDir + subDir + newFileName;
                    System.err.println(savePath);
                    try {
                        // 真实路径
                        file.transferTo(new File(savePath));
                        // 设置访问路径
                        commentImg.setCommentImg("pat_mall/commentImg/" + subDir + "/" + newFileName);
                    } catch (IOException e) {
                        map.put("code", 1);
                        // 提供错误信息
                        e.printStackTrace();
                    }
                }
                List<Comment> commentList = commentService.getComments(comment);
                commentImg.setCommentId(commentList.get(0).getCommentId());
                int row = commentImgService.addCommentImg(commentImg);
                if (row == 1) {
                    map.put("code", 0);
                    continue;
                } else {
                    map.put("code", 1);
                    break;
                }
            }
        }else {
            map.put("code", 1);
        }
        return map;
    }
    @PostMapping("findAllComment")
    @ResponseBody
    public Object findAllComment(int page,int limit){
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Comment> commentList = commentService.findAllComment();
        Page<Comment> pageList = (Page<Comment>) commentList;
        long count = pageList.toPageInfo().getTotal();
        map.put("code",0);
        map.put("msg", "这是数据传来的！");
        map.put("count", count);
        map.put("data", pageList);
        return map;
    }
    @PostMapping("updateComment")
    @ResponseBody
    public String updateComment(Comment comment){
        int count = commentService.updateComment(comment);
        if (count == 1){
            return "success";
        }else{
            return "fail";
        }
    }

    @PostMapping("getAllByCommentContent")
    @ResponseBody
    public Object getAllByCommentContent(int page,int limit,String commentContent){
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Comment> commentList = commentService.getAllByCommentContent(commentContent);
        Page<Comment> pageList = (Page<Comment>) commentList;
        long count = pageList.toPageInfo().getTotal();
        map.put("code",0);
        map.put("msg", "这是数据传来的！");
        map.put("count", count);
        map.put("data", pageList);
        return map;
    }
}
